import { createRouter, createWebHistory } from 'vue-router';
import Index from '@/views/index/index.vue';
import Role from '@/views/role/index.vue';
import User from '@/views/user/index.vue';
import Conveyor from '@/views/conveyor/index.vue';
import Inspector from '@/views/inspector/index.vue';
import Login from '@/views/login/index.vue';
import Layout from '@/views/layout/index.vue';
import Error from '@/views/error/index.vue';
import Auth from '@/views/auth/index.vue';

const routes = [
  { path: '/', 
    component: Layout,
    redirect: '/index',
   meta: { requiresAuth: true },
    children: [
      { path: '/index', component: Index, meta: { requiresAuth: true } },
      { path: '/role', component: Role, meta: { requiresAuth: true } },
      { path: '/user', component: User, meta: { requiresAuth: true } },
      { path: '/conveyor', component: Conveyor, meta: { requiresAuth: true } },
      { path: '/inspector', component: Inspector, meta: { requiresAuth: true } },
      { path: '/error', component: Error, meta: { requiresAuth: true } },
      { path: '/auth', component: Auth, meta: { requiresAuth: true } }
    ]
    //     children: [
    //   { path: '/index', component: Index },
    //   { path: '/role', component: Role },
    //   { path: '/user', component: User },
    //   { path: '/conveyor', component: Conveyor },
    //   { path: '/inspector', component: Inspector },
    //   { path: '/error', component: Error },
    //   { path: '/auth', component: Auth }
    // ]
  },
  
  { path: '/login', component: Login }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查目标路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查localStorage中是否有登录用户信息
    const loginUser = JSON.parse(localStorage.getItem('loginUser'));
    if (loginUser) {
      // 用户已登录，允许访问
      next();
    } else {
      // 用户未登录，重定向到登录页
      next('/login');
    }
  } else {
    // 不需要认证的路由，直接访问
    next();
  }
});

export default router;